import {getToken, removeToken} from './token';
import { EventSourcePolyfill } from 'event-source-polyfill';

// 将 this 类型调整为标准 EventSource，匹配事件处理函数的上下文要求
export const useSSE = (url: string, onMessage: (this: EventSource, ev: MessageEvent<any>) => void) => {
    const eventSource = new EventSourcePolyfill(url, {
        headers: {
            'Authorization': `Bearer ${getToken()}` // SSE请求携带Token
        }
    });

    eventSource.onmessage = onMessage;

    eventSource.onerror = (error: any) => {
        console.error('SSE error:', error);
        // 检测HTTP 401状态（部分浏览器/polyfill可能通过error.status传递）
        if (error.status === 401||error.status === 403) {
            removeToken();
            window.location.href = '/login';
        }
        eventSource.close();
    };

    return eventSource;
};
